package com.ynet.middleground.contract.utils;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.Serializable;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import org.apache.dubbo.config.annotation.Reference;
import org.dozer.Mapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import com.ynet.core.common.BaseReqObj;
import com.ynet.core.common.PagerInfo;
import com.ynet.core.common.ServiceResult;
import com.ynet.core.exception.BusinessException;
import com.ynet.file.starter.FileServiceConfiguration;
import com.ynet.middleground.approve.bean.CompleteTaskReq;
import com.ynet.middleground.approve.bean.ProcessInstanceReq;
import com.ynet.middleground.approve.bean.QueryRepeatStartProcessReq;
import com.ynet.middleground.approve.bean.StartProcessInstanceReq;
import com.ynet.middleground.approve.dto.ProcessInstanceDTO;
import com.ynet.middleground.approve.dto.TaskDTO;
import com.ynet.middleground.approve.service.ProcessInstanceService;
import com.ynet.middleground.approve.service.ProcessTaskService;
import com.ynet.middleground.contract.bean.ContractSubmissionReq;
import com.ynet.middleground.contract.bean.StartProcessInstance;
import com.ynet.middleground.contract.constant.SystemConsts;
import com.ynet.middleground.contract.constant.TemplateStatusEnum;
import com.ynet.middleground.contract.dao.ArchiveHistoryMapper;
import com.ynet.middleground.contract.dao.ContractHistoryMapper;
import com.ynet.middleground.contract.dao.ContractMapper;
import com.ynet.middleground.contract.dao.TemplateMapper;
import com.ynet.middleground.contract.entity.*;
import com.ynet.middleground.office.bean.Office2PdfReq;
import com.ynet.middleground.office.service.OfficeService;
import com.ynet.middleground.user.bean.QueryChannelReq;
import com.ynet.middleground.user.bean.QueryUserInfoReq;
import com.ynet.middleground.user.dto.ChannelCompanyDTO;
import com.ynet.middleground.user.dto.UserInfoDto;

import cfca.seal.util.StringUtil;

/**
 * @Description: 通用服务类，不存放静态方法
 * @Param:
 * @return:
 * @Author: DaiGaoLe
 * @Date: 2020-03-18
 */

@Component
public class GeneralService implements Serializable {
    /**
     * 审批服务类
     */
    @Reference(version = "0.0.1", check = false, protocol = "dubbo")
    ProcessInstanceService processInstanceService;

    /**
     * 审批流程服务类
     */
    @Reference(version = "0.0.1", check = false, protocol = "dubbo")
    ProcessTaskService processTaskService;

    /**
     * 用户管理服务类
     */
    @Reference(version = "0.0.1", check = false, protocol = "dubbo")
    com.ynet.middleground.user.service.UserService userService;

    /**
     * pfd文件转换服务
     */
    @Reference(version = "1.0.0", check = false, protocol = "dubbo", timeout = 60000)
    OfficeService officeService;

    /**
     * 复制属性工具
     */
    @Autowired
    private Mapper dozerBeanMapper;

    /**
     * 用户管理服务类
     */
    @Reference(version = "0.0.1", check = false, protocol = "dubbo")
    com.ynet.middleground.user.service.ChannelCompanyService channelCompanyService;

    /**
     * 合约主表dao
     */
    @Autowired
    private ContractMapper contractMapper;

    /**
     * 模版主表dao
     */
    @Autowired
    private TemplateMapper templateMapper;

    /**
     * oss服务操作类
     */
    @Autowired
    FileServiceConfiguration fileServiceConfiguration;

    @Autowired
    private CommUtils commUtils;

    /**
     * 成功的标识
     */
    public static final String SUCCESS_FLAG = "0";

    /**
     * 判断用户是否存在
     *
     * @param queryUserInfoReq 查询用户信息请求对象
     * @return boolean
     */
    public boolean isUserIdCorrect(QueryUserInfoReq queryUserInfoReq) {
        boolean correct = true;
        ServiceResult<List<UserInfoDto>> listServiceResult = userService.queryUserInfo(queryUserInfoReq);
        if (listServiceResult == null || !SUCCESS_FLAG.equals(listServiceResult.getErrorCode())) {
            return false;
        }
        if (listServiceResult.getResult() == null || listServiceResult.getResult().size() == 0) {
            return false;
        }
        return true;
    }

    /**
     * 获取用户信息
     *
     * @param baseReqObj 基础参数
     * @param userId 用户id
     * @return 查询用户信息请求对象
     */
    public QueryUserInfoReq getQueryUserInfoReq(BaseReqObj baseReqObj, Integer userId) {
        QueryUserInfoReq queryUserInfoReq = new QueryUserInfoReq();
        queryUserInfoReq.setPagerInfo(new PagerInfo());
        queryUserInfoReq.setChannel(baseReqObj.getChannel());
        queryUserInfoReq.setTraceId(baseReqObj.getTraceId());
        queryUserInfoReq.setOperationUserId(baseReqObj.getOperationUserId());
        queryUserInfoReq.setRequestTime(new Date());
        queryUserInfoReq.setUserId(userId);
        return queryUserInfoReq;
    }

    public static final String DATE_NUMBER_PATTERN = "yyyyMMdd";

    /**
     * 由日期返回yyyy-MM-dd格式的字符串
     *
     * @author DaiGaoLe
     * @Date 2020-03-19
     * @param date
     * @return
     */
    public Date stringToDate(String string) {
        if (string == null) {
            return null;
        }
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        try {
            return simpleDateFormat.parse(string);
        } catch (ParseException e) {
            throw new BusinessException("ECCT0718", e.getMessage());
        }
    }

    /**
     * 由日期返回yyyy-MM-dd格式的字符串
     *
     * @author DaiGaoLe
     * @Date 2020-03-19
     * @param date
     * @return
     */
    public Date stringToDate(String string, String format) {
        if (string == null) {
            return null;
        }
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(format);
        try {
            return simpleDateFormat.parse(string);
        } catch (ParseException e) {
            throw new BusinessException("ECCT0718", e.getMessage());
        }
    }

    /**
     * 由日期返回yyyyMMdd格式的字符串
     *
     * @author DaiGaoLe
     * @Date 2020-03-19
     * @param date
     * @return
     */
    public Date numberToDate(String string) {
        if (string == null) {
            return null;
        }
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(DATE_NUMBER_PATTERN);
        try {
            return simpleDateFormat.parse(string);
        } catch (ParseException e) {
            throw new BusinessException("时间格式不正确", "ECCT0109");
        }
    }

    /**
     * @param contract 合约对象
     * @param operationUserId 操作人id
     * @param isUpdate 是否更新
     */
    public void contractUpdateOperationIdAndDate(Contract contract, Integer operationUserId, Boolean isUpdate) {
        if (isUpdate) {
            // 修改人
            contract.setModifiedBy(operationUserId);
            // 修改时间
            contract.setGmtModified(LocalDateTime.now());
        } else {
            // 创建人
            contract.setCreateBy(operationUserId);
            // 创建时间
            contract.setGmtCreate(LocalDateTime.now());
            // 修改人
            contract.setModifiedBy(operationUserId);
            // 修改时间
            contract.setGmtModified(LocalDateTime.now());
        }

    }

    /**
     *
     * @param archive 档案对象
     * @param operationUserId 操作人id
     * @param isUpdate 是否更新
     */
    public void archiveUpdateOperationIdAndDate(Archive archive, Integer operationUserId, Boolean isUpdate) {
        if (isUpdate) {
            // 修改人
            archive.setModifiedBy(operationUserId);
            // 修改时间
            archive.setGmtModified(LocalDateTime.now());
        } else {
            // 创建人
            archive.setCreateBy(operationUserId);
            // 创建时间
            archive.setGmtCreate(LocalDateTime.now());
            // 修改人
            archive.setModifiedBy(operationUserId);
            // 修改时间
            archive.setGmtModified(LocalDateTime.now());
        }

    }

    /**
     * 档案dao
     */
    @Autowired
    ArchiveHistoryMapper archiveHistoryMapper;

    /**
     * 合约历史dao
     */
    @Autowired
    ContractHistoryMapper contractHistoryMapper;

    /**
     * 档案历史记录表
     *
     * @param archive 档案对象
     */
    public void insertArchiveHistory(Archive archive) {
        ArchiveHistory archiveHistory = dozerBeanMapper.map(archive, ArchiveHistory.class);
        archiveHistory.setArchiveId(archive.getId());
        archiveHistoryMapper.insert(archiveHistory);
    }

    /**
     * 合约历史记录表保存
     *
     * @param contract 合约对象
     */
    public void insertContractHistory(Contract contract) {
        ContractHistory contractHistory = dozerBeanMapper.map(contract, ContractHistory.class);
        contractHistory.setContractId(contract.getId());
        contractHistoryMapper.insert(contractHistory);
    }

    /**
     * 判断当前模版是不是最新模版
     */
    public void checkCurrentVersion(Template template) {
        if (TemplateStatusEnum.EXPIRE.getCode().equals(template.getStatus())) {
            throw new BusinessException("请使用当前合约模板最新版本", "ECCT0105");
        }
    }

    public static final String FULL_DATE_NUMBER = "yyyyMMddHHmmss";

    /**
     * 由日期返回yyyyMMddHHmmss格式的字符串
     *
     * @author DaiGaoLe
     * @Date 2019-10-17
     * @param time
     * @return
     */
    public static String timeToNumber(Date time) {
        if (time == null) {
            return null;
        }

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(FULL_DATE_NUMBER);
        return simpleDateFormat.format(time);
    }

    /**
     * 由日期返回yyyyMMdd格式的字符串
     *
     * @author SongYiFan
     * @Date 2020-07-13
     * @param time
     * @return
     */
    public static String timeToNumberYMD(Date time) {
        if (time == null) {
            return null;
        }

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(DATE_NUMBER_PATTERN);
        return simpleDateFormat.format(time);
    }

    /**
     * 获取合约编号合约编号
     *
     * @param channel 渠道
     * @param productType 产品类型
     * @param contractTypeCode 合约类型
     * @param contractId 合约id
     * @return
     */
    public String getContractNo(String channel, String companyCode, String contractTypeCode, Integer contractId,
        BaseReqObj base) {
        QueryChannelReq queryChannelReq = new QueryChannelReq();
        queryChannelReq.setChannelCode(channel);
        queryChannelReq.setChannel(channel);
        queryChannelReq.setOperationUserId(base.getOperationUserId());
        queryChannelReq.setRequestTime(base.getRequestTime());
        queryChannelReq.setTraceId(base.getTraceId());
        List<ChannelCompanyDTO> channelCompanyReqList =
            channelCompanyService.listByChannelCode(queryChannelReq).getResult();
        boolean haveCorpName = false;
        if (channelCompanyReqList != null) {
            Iterator<ChannelCompanyDTO> iterator = channelCompanyReqList.iterator();
            while (iterator.hasNext()) {
                if (companyCode.equals(iterator.next().getCompanyCode())) {
                    haveCorpName = true;
                    break;
                }
            }
        }
        if (!haveCorpName) {
            throw new BusinessException("公司编码不正确", "ECCT0739");
        } else {
            // 若id小于六位则补零，当大于六位时重置
            String newContractId = Integer.toString(contractId);
            if (newContractId.length() < 7) {
                for (; newContractId.length() < 6;) {
                    newContractId = "0" + newContractId;
                }
            } else {
                newContractId = newContractId.substring(newContractId.length() - 6, newContractId.length());
            }
            // 合约编号生成规则：渠道+公司编码+合约类型+合约保存时间+编号
            String contractNo = channel + companyCode + contractTypeCode + timeToNumberYMD(new Date()) + newContractId;
            return contractNo;
        }
    }

    /**
     * 合约id是否有效
     *
     * @param contractId 合约di
     * @return 合约对象
     */
    public Contract verifyContractIdEffective(Integer contractId) {
        Contract contract = contractMapper.selectById(contractId);
        // 合约id必须存在且有效
        if (contract == null) {
            throw new BusinessException("ECCT0703", "合约id无效");
        }
        if (!Integer.valueOf(SystemConsts.IS_DELETED_0).equals(contract.getIsDeleted())) {
            throw new BusinessException("ECCT0728", "合约已经被删除");
        }
        return contract;
    }

    /**
     * 判断是否为制式合约
     *
     * @param contractType 合约类型
     * @param templateId 模版id
     */
    public void isOfficialContract(String contractType, Integer templateId) {
        if (SystemConsts.CONTRACT_TYPE_0.equals(contractType)) {
            if (templateId == null) {
                throw new BusinessException("ECCT0703", "模版id不能唯空");
            }
        }
    }

    /**
     * 校验模版
     *
     * @param templateId 模版id
     * @param channel 渠道
     * @return 模版对象
     */
    public Template getTemplate(Integer templateId, String channel) {
        if (channel == null) {
            throw new BusinessException("ECCT0731", "当前渠道不能为空");
        }

        Template templateBase = templateMapper.selectById(templateId);
        if (templateBase == null) {
            throw new BusinessException("ECCT0100", "模版不存在");
        }

        if (!channel.equals(templateBase.getChannel())) {
            throw new BusinessException("ECCT0705", "上送渠道和当前渠道不一致");
        }

        if (templateBase.getIsDeleted()) {
            throw new BusinessException("ECCT0732", "当前模版已经被删除不能使用");
        }

        if (!TemplateStatusEnum.ACTIVATED.getCode().equals(templateBase.getStatus())) {
            throw new BusinessException("ECCT0117", "当前合约模板未启用");
        }

        // 模板 id 对应模板必须为最新版本
        checkCurrentVersion(templateBase);
        return templateBase;
    }

    /**
     * 校验上级是否有效
     *
     * @param parentId 上级id
     * @return
     */
    public Contract getParentContractById(Integer parentId) {
        Contract parentContract = null;
        parentContract = contractMapper.selectById(parentId);
        if (parentContract == null) {
            throw new BusinessException("ECCT0702", "上级合约id不存在");
        }

        return parentContract;
    }

    /**
     * 合约没有被删除，状态是以签署的合约，如果不是提示错误
     *
     * @param id 合约id
     * @return 合约对象
     */
    public Contract checkContractById(Integer id) {
        QueryWrapper<Contract> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", id);
        queryWrapper.eq("is_deleted", 0);
        queryWrapper.eq("status", SystemConsts.CONTRACT_STATUS_2);
        Contract parentContract = contractMapper.selectOne(queryWrapper);
        if (parentContract == null) {
            throw new BusinessException("ECCT0703", "合约id无效");
        }
        return parentContract;
    }

    /**
     * 根据id获取合约
     *
     * @param id 合约id
     * @return 合约对象
     */
    public Contract getContractById(Integer id) {
        QueryWrapper<Contract> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", id);
        queryWrapper.eq("is_deleted", 0);
        queryWrapper.eq("status", SystemConsts.CONTRACT_STATUS_0);
        Contract parentContract = contractMapper.selectOne(queryWrapper);
        if (parentContract == null) {
            throw new BusinessException("ECCT0703", "合约id无效");
        }
        return parentContract;
    }

    /**
     * 生成二维码流
     *
     * @param text 内容
     * @param width 宽度
     * @param height 高度
     * @return 二维码流
     */
    public byte[] getQRCodeImage(String text, int width, int height) {
        QRCodeWriter qrCodeWriter = new QRCodeWriter();
        BitMatrix bitMatrix = null;
        try {
            bitMatrix = qrCodeWriter.encode(text, BarcodeFormat.QR_CODE, width, height);
        } catch (WriterException e) {
            throw new BusinessException("ECCT0702", "二维码错误");
        }
        ByteArrayOutputStream pngOutputStream = new ByteArrayOutputStream();
        try {
            MatrixToImageWriter.writeToStream(bitMatrix, "PNG", pngOutputStream);
        } catch (IOException e) {
            throw new BusinessException("ECCT0702", "二维码错误");
        }
        byte[] pngData = pngOutputStream.toByteArray();
        return pngData;
    }

    /**
     * LocalDateTime转换为Date
     *
     * @param localDateTime 时间对象
     */
    public Date localDateTime2Date(LocalDateTime localDateTime) {
        ZoneId zoneId = ZoneId.systemDefault();
        ZonedDateTime zdt = localDateTime.atZone(zoneId);
        Date date = Date.from(zdt.toInstant());
        return date;
    }

    /**
     * 流程实例id
     *
     * @param requestObj 确认提交合约对象
     * @param contractNo 合约编号
     * @return
     */
    public String startProcessInstance(ContractSubmissionReq requestObj, String contractNo) {
        StartProcessInstance startProcessInstance = requestObj.getStartProcessInstance();
        if (startProcessInstance == null) {
            throw new BusinessException("ECCT0725", "启动流程参数不能为空");
        }
        String appProcessNo = null;
        StartProcessInstanceReq startProcessInstanceReq = new StartProcessInstanceReq();
        startProcessInstanceReq.setChannel(requestObj.getChannel());
        startProcessInstanceReq.setOperationUserId(requestObj.getOperationUserId());
        startProcessInstanceReq.setTraceId(requestObj.getTraceId());
        startProcessInstanceReq.setRequestTime(requestObj.getRequestTime());
        startProcessInstanceReq.setBusinessKey(contractNo);
        startProcessInstanceReq.setStartUserId(String.valueOf(requestObj.getOperationUserId()));
        startProcessInstanceReq.setProcessDefinitionKey(requestObj.getStartProcessInstance().getProcessDefinitionKey());
        ServiceResult<String> stringServiceResult =
            processInstanceService.startProcessInstance(startProcessInstanceReq);
        if (stringServiceResult != null && SUCCESS_FLAG.equals(stringServiceResult.getErrorCode())) {
            return stringServiceResult.getResult();
        } else {
            throw new BusinessException(stringServiceResult.getErrorCode(), stringServiceResult.getErrorMsg());
        }
    }

    /**
     * 检查重复起动过程
     *
     * @param requestObj 确认提交合约对象
     */
    public void checkRepeatStartProcess(ContractSubmissionReq requestObj) {
        QueryRepeatStartProcessReq queryRepeatStartProcessReq = new QueryRepeatStartProcessReq();
        queryRepeatStartProcessReq.setChannel(requestObj.getChannel());
        queryRepeatStartProcessReq.setOperationUserId(requestObj.getOperationUserId());
        queryRepeatStartProcessReq.setTraceId(requestObj.getTraceId());
        queryRepeatStartProcessReq.setRequestTime(requestObj.getRequestTime());
        queryRepeatStartProcessReq
            .setProcessDefinitionKey(requestObj.getStartProcessInstance().getProcessDefinitionKey());
        queryRepeatStartProcessReq.setStartUserId(String.valueOf(requestObj.getOperationUserId()));
        ServiceResult serviceResult = processInstanceService.checkRepeatStartProcess(queryRepeatStartProcessReq);
        if (serviceResult != null && !SUCCESS_FLAG.equals(serviceResult.getErrorCode())) {
            throw new BusinessException(serviceResult.getErrorCode(), serviceResult.getErrorMsg());
        }

    }

    /**
     * 完成任务
     *
     * @param requestObj 确认提交合约对象
     * @param appProcessNo 流程实例id
     */
    public void completeTask(ContractSubmissionReq requestObj, String appProcessNo) {
        TaskDTO taskDTO = null;
        ProcessInstanceReq processInstanceReq = new ProcessInstanceReq();
        processInstanceReq.setChannel(requestObj.getChannel());
        processInstanceReq.setOperationUserId(requestObj.getOperationUserId());
        processInstanceReq.setTraceId(requestObj.getTraceId());
        processInstanceReq.setRequestTime(requestObj.getRequestTime());
        processInstanceReq.setProcessInstanceId(appProcessNo);
        ServiceResult<List<TaskDTO>> activeTaskByInstanceId =
            processTaskService.getActiveTaskByInstanceId(processInstanceReq);
        if (activeTaskByInstanceId != null && SUCCESS_FLAG.equals(activeTaskByInstanceId.getErrorCode())) {
            if (activeTaskByInstanceId.getResult() != null) {
                taskDTO = activeTaskByInstanceId.getResult().get(0);
            }
        } else {
            throw new BusinessException(activeTaskByInstanceId.getErrorCode(), activeTaskByInstanceId.getErrorMsg());
        }
        CompleteTaskReq completeTaskReq = new CompleteTaskReq();
        completeTaskReq.setChannel(requestObj.getChannel());
        completeTaskReq.setOperationUserId(requestObj.getOperationUserId());
        completeTaskReq.setTraceId(requestObj.getTraceId());
        completeTaskReq.setRequestTime(requestObj.getRequestTime());
        completeTaskReq.setTaskId(taskDTO.getId());
        // 审批人使用id
        completeTaskReq.setAssignee(requestObj.getOperationUserId().toString());
        completeTaskReq.setApproveResult(1);
        if (StringUtil.isNotEmpty(requestObj.getCompleteTask().getComment())) {
            completeTaskReq.setComment(requestObj.getCompleteTask().getComment());
        }

        if (requestObj.getCompleteTask().getProcessVariables() != null) {
            completeTaskReq.setProcessVariables(requestObj.getCompleteTask().getProcessVariables());
        }

        if (requestObj.getCompleteTask().getVariables() != null) {
            completeTaskReq.setVariables(requestObj.getCompleteTask().getVariables());
        }
        ServiceResult serviceResult = processTaskService.completeTask(completeTaskReq);

        if (serviceResult != null && SUCCESS_FLAG.equals(serviceResult.getErrorCode())) {
            return;
        } else {
            throw new BusinessException(serviceResult.getErrorCode(), serviceResult.getErrorMsg());
        }
    }

    /**
     * PDF url
     *
     * @param fileUrl 文件短路径地址
     * @param requestObj 基础参数
     * @return PDF url
     */
    public String generatePDF(String fileUrl, BaseReqObj requestObj) {
        Office2PdfReq req = new Office2PdfReq();
        req.setChannel(requestObj.getChannel());
        req.setOperationUserId(requestObj.getOperationUserId());
        req.setTraceId(requestObj.getTraceId());
        req.setRequestTime(requestObj.getRequestTime());
        // 短路径转为完整路径
        String ossFullUrl = commUtils.getOssFullUrl(fileUrl);
        req.setFileUrl(ossFullUrl);
        ServiceResult<String> serviceResult = officeService.word2Pdf(req);
        if (serviceResult.getResult() != null && serviceResult.isSuccess()) {// 成功
            // 格式zhongtai/名字
            String result = serviceResult.getResult();
            if (result == null) {
                throw new BusinessException(serviceResult.getErrorCode(), serviceResult.getErrorMsg());
            }
            // 直接返回短路径
            return result;
            // 拼接完整路径
            // String endpoint = fileServiceConfiguration.getConfigs().get(0).getOssConfig().getEndpoint();
            // return endpoint.substring(0, endpoint.lastIndexOf("/")) + "/" + result;
        }
        throw new BusinessException("ECCT0727", "pdf转换异常");
    }

    /**
     * 删除合同时候用的 合约不能有在途流程
     *
     * @param appProcessNo 流程实例id
     * @param requestObj 基础参数
     */
    public void checkOnTheProcess(String appProcessNo, BaseReqObj requestObj) {
        if (StringUtil.isNotEmpty(appProcessNo)) {
            ProcessInstanceReq processInstanceReq = new ProcessInstanceReq();
            processInstanceReq.setChannel(requestObj.getChannel());
            processInstanceReq.setOperationUserId(requestObj.getOperationUserId());
            processInstanceReq.setTraceId(requestObj.getTraceId());
            processInstanceReq.setRequestTime(requestObj.getRequestTime());
            processInstanceReq.setProcessInstanceId(appProcessNo);
            ServiceResult<ProcessInstanceDTO> finishProcess =
                processInstanceService.isFinishProcess(processInstanceReq);
            if (finishProcess != null && finishProcess.isSuccess()) {
                if (finishProcess.getResult() != null) {// 有在途流程
                    throw new BusinessException("当前合约有在途流程", "ECCT0738");
                }
            } else {
                throw new BusinessException(finishProcess.getErrorCode(), finishProcess.getErrorMsg());
            }

        }
    }

    /**
     * Date 转 LocalDateTime
     *
     * @param date 时间
     * @return LocalDateTime
     */
    public LocalDateTime dateToLocalDateTime(Date date) {
        Instant instant = date.toInstant();
        ZoneId zoneId = ZoneId.systemDefault();

        LocalDateTime localDateTime = instant.atZone(zoneId).toLocalDateTime();
        return localDateTime;
    }

    /**
     * 字符串转LocalDateTime
     *
     * @param dateString 时间字符串
     * @param format 时间格式
     * @return LocalDateTime
     */
    public LocalDateTime dateToLocalDateTime(String dateString, String format) {
        if (dateString == null) {
            throw new BusinessException("ECCT0109", "时间格式不正确");
        }

        if (StringUtil.isEmpty(format)) {
            format = "yyyy-MM-dd HH:mm:ss";
        }

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(format);
        Date date = null;
        try {
            date = simpleDateFormat.parse(dateString);
        } catch (ParseException e) {
            throw new BusinessException("ECCT0109", "时间格式不正确");
        }
        Instant instant = date.toInstant();
        ZoneId zoneId = ZoneId.systemDefault();

        LocalDateTime localDateTime = instant.atZone(zoneId).toLocalDateTime();
        return localDateTime;
    }

    /**
     * 将短时间格式时间转换为字符串 yyyy-MM-dd
     *
     * @param dateDate
     * @return yyyy-MM-dd
     */
    public String dateToStr(Date dateDate) {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        String dateString = formatter.format(dateDate);
        return dateString;
    }
}
